package com.hivekion.common.exception;

import com.hivekion.common.entity.BusinessExceptionInfo;
import com.hivekion.common.enums.ResultCodeEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice
@Order(value = Ordered.HIGHEST_PRECEDENCE)
public class ExceptionHandle {
      private static final Logger logger = LoggerFactory.getLogger(ExceptionHandle.class);

      /**
       * 判断错误是否是已定义的已知错误，不是则由未知错误代替，同时记录在log中
       *
       * @param e
       * @return
       */
      @ExceptionHandler(value = BusinessException.class)
      @ResponseBody
      public BusinessExceptionInfo exceptionGet(Throwable e) {
	    BusinessExceptionInfo info = new BusinessExceptionInfo();
	    if (e instanceof BusinessException) {
		  BeanUtils.copyProperties(e, info);
		  logger.error("自定义异常", e);
		  return info;
	    }
	    if (e instanceof Exception) {
		  info.setCode(ResultCodeEnum.SYSTEM_ERROR.getCode());
		  info.setMessage(e.getMessage());
		  logger.error("系统异常", e);
		  return info;
	    }
	    return null;
      }
}
